package cn.acewill.yxd.yunxundian.ui.schedule;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TimePicker;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.componet.NetWorkStateReceiver;
import cn.acewill.yxd.yunxundian.model.Employee;
import cn.acewill.yxd.yunxundian.model.Schedule;
import cn.acewill.yxd.yunxundian.model.Shop;
import cn.acewill.yxd.yunxundian.model.sType;
import cn.acewill.yxd.yunxundian.pubClass.SimpleSpinnerOption;
import cn.acewill.yxd.yunxundian.pubClass.multiSelect;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.ui.MainActivity;

import static cn.acewill.yxd.yunxundian.pubClass.pubClass.Server_namehzm;

public class tuisongSchedule extends BaseActivity {

    protected TextView toUser,toShop,toRenwu,toDay,toTime;
    protected LinearLayout rRen,rRenwu,rCanting,rRiqi,rShijian;
    protected static Schedule tempSch=new Schedule();
    public Context mContext;
    private List<SimpleSpinnerOption> emplst=new ArrayList<>();
    private List<SimpleSpinnerOption> shoplst=new ArrayList<>();
    private List<SimpleSpinnerOption> stypelst=new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tuisong_schedule);
        mContext=this;
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setTitle("任务推送");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowCustomEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final Snackbar snackbar=Snackbar.make(view, "请稍后，正在推送任务...", Snackbar.LENGTH_LONG)
                        .setAction("Action", null);
                snackbar.show();
                tempSch.setSchStartTime(toDay.getText()+" "+toTime.getText());
                tempSch.setStartUserId(MainActivity.id);

                if(tempSch.getToUserId()==0)
                {
                    snackbar.setText("请选择推送人");
                    return;
                }
                if(tempSch.getSchStartTime()==null||tempSch.getSchStartTime().equals(" "))
                {
                    snackbar.setText("请选择时间");
                    return;
                }
                if(tempSch.getSTypeID()==0)
                {
                    snackbar.setText("请选择任务");
                    return;
                }
                if(tempSch.getShopID()==0)
                {
                    snackbar.setText("请选择餐厅");
                    return;
                }
                Gson gson=new Gson();
                Map<String,Object> map=new HashMap<>();
                map.put("task","toomsch");
                map.put("empid",MainActivity.id+"");
                map.put("schjson",gson.toJson(tempSch));
                if (NetWorkStateReceiver.whetherConnectNetWork==1){
                    pubClass.Post(Server_namehzm,map,new pubClass.MyCallBack<String>(){
                        @Override
                        public void onSuccess(String result) {
                            super.onSuccess(result);
                            String[] strings=result.split("\\|");
                            if(strings[0].equals("200")) {
                                tempSch=new Schedule();
                                toUser.setText("");
                                toShop.setText("");
                                toRenwu.setText("");
                                snackbar.setText("推送成功");
                                snackbar.setDuration(1500);
                            }
                        }
                        @Override
                        public void onError(Throwable ex, boolean isOnCallback) {
                            super.onError(ex, isOnCallback);
                            snackbar.setText("推送失败请稍后再试");
                            snackbar.setDuration(1500);
                        }
                    });
                }
            }
        });
        rRen=(LinearLayout)findViewById(R.id.row1);
        rRenwu=(LinearLayout)findViewById(R.id.row00);
        rCanting=(LinearLayout)findViewById(R.id.row3);
        rRiqi=(LinearLayout)findViewById(R.id.row5);
        rShijian=(LinearLayout)findViewById(R.id.row7);

        toUser=(TextView)findViewById(R.id.jieshouren);
        toShop=(TextView)findViewById(R.id.shopid);
        toRenwu=(TextView)findViewById(R.id.schtype);
        toDay=(TextView)findViewById(R.id.riqi);
        toTime=(TextView)findViewById(R.id.shijian);

        Map<String,Object> map=new HashMap<>();
        map.put("task","loadSubEmps");
        map.put("empid",MainActivity.id+"");
        if(emplst!=null)
            emplst.clear();
        if (NetWorkStateReceiver.whetherConnectNetWork==1){
            pubClass.Post(Server_namehzm,map,new pubClass.MyCallBack<String>(){
                @Override
                public void onSuccess(String result) {
                    super.onSuccess(result);
                    String[] strings=result.split("\\|");
                    if(strings[0].equals("200")) {
                        //json转化为对象；
                        Gson gson = new Gson();
                        Type typeList = new TypeToken<ArrayList<Employee>>() {
                        }.getType();
                        List<Employee> shopList = gson.fromJson(pubClass.convertToArrayJson(result), typeList);
                        if(shopList!=null)
                        {
                            for(Employee emp :shopList)
                            {
                                SimpleSpinnerOption sso=new SimpleSpinnerOption();
                                sso.setChecked(false);
                                sso.setName(emp.getFirstName());
                                sso.setValue(emp.getID()+"");
                                emplst.add(sso);
                            }

                        }
                    }
                }
                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    super.onError(ex, isOnCallback);
                }
            });
        }

        map=new HashMap<>();
        map.put("task","loadSubEmpsStype");
        map.put("empid",MainActivity.id+"");


        if(stypelst!=null)
            stypelst.clear();
        if (NetWorkStateReceiver.whetherConnectNetWork==1){
            pubClass.Post(Server_namehzm,map,new pubClass.MyCallBack<String>(){
                @Override
                public void onSuccess(String result) {
                    super.onSuccess(result);
                    String[] strings=result.split("\\|");
                    if(strings[0].equals("200")) {
                        //json转化为对象；
                        Gson gson = new Gson();
                        Type typeList = new TypeToken<ArrayList<sType>>() {
                        }.getType();
                        List<sType> schList = gson.fromJson(pubClass.convertToArrayJson(result), typeList);
                        if(schList!=null)
                        {
                            for(sType stype :schList)
                            {
                                SimpleSpinnerOption sso=new SimpleSpinnerOption();
                                sso.setChecked(false);
                                sso.setName(stype.getTypeName());
                                sso.setValue(stype.getID()+"");
                                stypelst.add(sso);
                            }
                        }
                    }
                }
                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    super.onError(ex, isOnCallback);
                }
            });
        }
        map=new HashMap<>();
        map.put("task","loadSubShop");
        map.put("empid",MainActivity.id+"");
        if(shoplst!=null)
            shoplst.clear();
        if (NetWorkStateReceiver.whetherConnectNetWork==1){
            pubClass.Post(mContext,Server_namehzm,map,new pubClass.MyCallBack<String>(){
                @Override
                public void onSuccess(String result) {
                    super.onSuccess(result);
                    String[] strings=result.split("\\|");
                    if(strings[0].equals("200")) {
                        //json转化为对象；
                        Gson gson = new Gson();
                        Type typeList = new TypeToken<ArrayList<Shop>>() {
                        }.getType();
                        List<Shop> shopList = gson.fromJson(pubClass.convertToArrayJson(result), typeList);
                        if(shopList!=null)
                        {
                            for(Shop shop :shopList)
                            {
                                SimpleSpinnerOption sso=new SimpleSpinnerOption();
                                sso.setChecked(false);
                                sso.setName(shop.getShopName());
                                sso.setValue(shop.getID()+"");
                                shoplst.add(sso);
                            }

                        }
                    }
                }
                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    super.onError(ex, isOnCallback);
                }
            });
        }





        rRen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(emplst!=null &&emplst.size()>0) {
                    Intent sel = new Intent(mContext, multiSelect.class);
                    sel.putExtra("lstData", JSON.toJSONString(emplst));
                    sel.putExtra("title", "请选择被推送人");
                    sel.putExtra("xuanze", "dan");
                    sel.putExtra("daima", "sch");
                    //startActivity(sel);
                    startActivityForResult(sel, 1);
                }
                else
                    BaseActivity.showAnimaDialog(mContext,"没有获取到推送人");
            }
        });

        rRenwu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent sel = new Intent(mContext, multiSelect.class);
                sel.putExtra("lstData", JSON.toJSONString(stypelst));
                sel.putExtra("title", "请选择任务");
                sel.putExtra("xuanze", "dan");
                sel.putExtra("daima", "sch");
                //startActivity(sel);
                startActivityForResult(sel, 2);
            }
        });
        rCanting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent sel = new Intent(mContext, multiSelect.class);
                sel.putExtra("lstData", JSON.toJSONString(shoplst));
                sel.putExtra("title", "请选择门店");
                sel.putExtra("xuanze", "dan");
                sel.putExtra("daima", "sch");
                //startActivity(sel);
                startActivityForResult(sel, 3);
            }
        });
        final Calendar c = Calendar.getInstance();
        final int year=c.get(Calendar.YEAR);
        final int month=c.get(Calendar.MONTH)+1;
        final int day=c.get(Calendar.DAY_OF_MONTH);
//        final int hour=c.get(Calendar.HOUR_OF_DAY);
//        final int minutes=0;

        rRiqi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DatePickerDialog dpd = new DatePickerDialog(mContext, Datelistener, year, month-1, day);
                dpd.show();
            }
            DatePickerDialog.OnDateSetListener Datelistener = new DatePickerDialog.OnDateSetListener() {
                /**
                 * params：view：该事件关联的组件
                 * params：myyear：当前选择的年
                 * params：monthOfYear：当前选择的月
                 * params：dayOfMonth：当前选择的日
                 */
                @Override
                public void onDateSet(DatePicker view, int myyear, int monthOfYear, int dayOfMonth) {
                    String showMonth=(monthOfYear+1)+"";
                    String showDay=dayOfMonth+"";
                    if(showMonth.length()==1)
                    {
                        showMonth="0"+showMonth;
                    }
                    if(showDay.length()==1)
                    {
                        showDay="0"+showDay;
                    }

                    toDay.setText(myyear+"-"+showMonth+"-"+showDay);
                }
            };

        });
        rShijian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimePickerDialog tpd = new TimePickerDialog(mContext,timeSetListener,12,0,true);
                tpd.show();//显示DatePickerDialog组件
            }
            TimePickerDialog.OnTimeSetListener timeSetListener=new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                    String showhour=hourOfDay+"";
                    String shoumin=minute+"";
                    if(showhour.length()==1)
                    {
                        showhour="0"+showhour;
                    }
                    if(shoumin.length()==1)
                    {
                        shoumin="0"+shoumin;
                    }

                    toTime.setText(showhour+":"+shoumin);
                }
            };
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Gson gson = new Gson();
        Type typeList = new TypeToken<ArrayList<SimpleSpinnerOption>>() {
        }.getType();
        if(resultCode==0)
            return;
        switch (requestCode) { //resultCode为回传的标记，我在B中回传的是RESULT_OK
            case 1:
                emplst=gson.fromJson(data.getStringExtra("result"),typeList);
                for(SimpleSpinnerOption sso:emplst)
                {
                    if(sso.isChecked())
                    {
                        tempSch.setToUserId(Integer.parseInt( sso.getValue().toString()));
                        toUser.setText(sso.getName());
                        break;
                    }
                }
                break;
            case 2:
                stypelst=gson.fromJson(data.getStringExtra("result"),typeList);
                for(SimpleSpinnerOption sso:stypelst)
                {
                    if(sso.isChecked())
                    {
                        tempSch.setSTypeID(Integer.parseInt(sso.getValue().toString()));
                        toRenwu.setText(sso.getName());
                        break;
                    }
                }
                break;
            case 3:
                shoplst=gson.fromJson(data.getStringExtra("result"),typeList);
                for(SimpleSpinnerOption sso:shoplst)
                {
                    if(sso.isChecked())
                    {
                        tempSch.setShopID(Integer.parseInt(sso.getValue().toString()));
                        toShop.setText(sso.getName());
                        break;
                    }
                }
                break;
            default:
                break;
        }
    }
}
